package com.masterclient.app.widget;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.ams.common.util.StringUtil;
import com.eoner.baselib.presenter.ThrowableConsumer;
import com.eoner.baselib.utils.notify.RxBus;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselibrary.BuildConfig;
import com.eoner.baselibrary.utils.LoadCallBack;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselibrary.utils.StringsUtils;
import com.eoner.baselibrary.utils.TimeUtil;
import com.eoner.baselibrary.utils.UIUtils;
import com.eoner.baselibrary.utils.Utils;
import com.eoner.baselibrary.utils.ViewTransformUtil;
import com.eoner.baselibrary.widget.PermissionDialog;
import com.eoner.common.bean.base.CommonBaseBean;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.Tools;
import com.eoner.managerlibrary.weixin.WeiXinManager;
import com.eoner.middlelib.eventbus.EventBusManager;
import com.eoner.middlelib.eventbus.event.WXSendCancelEvent;
import com.eoner.middlelib.eventbus.event.WXSendFailedEvent;
import com.eoner.middlelib.eventbus.event.WXSendSuccessEvent;
import com.gyf.immersionbar.ImmersionBar;
import com.masterclient.app.R;
import com.masterclient.app.httpservice.RetrofitUtil;
import com.masterclient.app.modules.goods.beans.ShareProductBean;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.eoner.baselibrary.utils.Utils.bmpToByteArray;

/**
 * @auther hjian
 * @date 2019/9/5.
 */
public class ShareNewCommonDialog extends Dialog {


    @BindView(R.id.share_ll)
    LinearLayout shareLl;
    @BindView(R.id.share_pic_rl)
    RelativeLayout sharePicRl;
    @BindView(R.id.ll_wx)
    LinearLayout llWx;
    @BindView(R.id.ll_pyq)
    LinearLayout llPyq;
    @BindView(R.id.ll_qr)
    LinearLayout llQr;
    @BindView(R.id.share_bottom_ll)
    LinearLayout shareBottomLl;
    @BindView(R.id.share_close)
    ImageView shareClose;

    @BindView(R.id.share_scroll)
    ScrollView shareScroll;
    @BindView(R.id.share_goodsdetail_ll)
    View shareGoodsdetailLl;
    @BindView(R.id.share_product_img)
    ImageView shareProductImg;
    @BindView(R.id.tv_sub_name)
    TextView tvSubName;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_category_name)
    TextView tv_category_name;
    @BindView(R.id.tv_show_phone)
    TextView tv_show_phone;
    @BindView(R.id.tv_show_man)
    TextView tv_show_man;
    @BindView(R.id.iv_qr_code)
    ImageView ivQrCode;
    @BindView(R.id.iv_sgs)
    ImageView ivSgs;

    @BindView(R.id.view_share_pic)
    View view_share_pic;
    @BindView(R.id.view_share_link)
    View view_share_link;



    private RxBus rxBus;
    private Activity context;
    private String title, url, subTitle, imgUrl, jump_type, path, mini_program_url;
    private boolean isLink = true;
    private RxPermissions rxPermissions;
    private int product_type;
    private Bitmap bitmap;
    private int shareType = -1;
    private Disposable disposable;

    private static final String ORIGINAL_ID = "gh_0d1a6e2f60fa";// 小程序原始id
    private static final String APP_ID = "wx8031a358899ba015";
    private String commission;
    private String sPageType, sPageId, sProductId, sProductName, sPageName, sPageUrl;
    private Map<String, String> map;
    private boolean showBottom =false;

    public ShareNewCommonDialog(@NonNull Activity context,boolean showBottom) {
        super(context, R.style.MyDialog);
        this.context = context;
        rxBus = RxBus.$();
        rxPermissions = new RxPermissions(context);
        map = new HashMap<>();
        this.showBottom = showBottom;
    }

    public void setShareData(String name, String image, String share_url, String show_man,
                             String show_phone, String category_name, String iconUrl) {
        isLink = false;
        view_share_pic.setVisibility(View.VISIBLE);
        view_share_link.setVisibility(View.GONE);
        tvSubName.setText(show_man+"作品");
        tvTitle.setText(name);
        tv_category_name.setText("类型："+category_name);
        tv_show_phone.setText("电话："+show_phone);
        tv_show_man.setText("展商："+show_man);
        ViewTransformUtil.glideImageView(context, image, shareProductImg, R.mipmap.defaults);
        if (!TextUtils.isEmpty(iconUrl)){
            ivSgs.setVisibility(View.VISIBLE);
            ViewTransformUtil.glideImageView(context, iconUrl, ivSgs, R.mipmap.defaults);
        }else {
            ivSgs.setVisibility(View.GONE);
        }
        ivQrCode.setImageBitmap(Tools.createQRImage(StringsUtils.urlAddParameters(share_url, map), ScreenUtils.dp2px(64), ScreenUtils.dp2px(64)
                , BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher)));

    }

    public void setShareLinkData(String url, String title, String desc, String image) {
        view_share_pic.setVisibility(View.GONE);
        view_share_link.setVisibility(View.VISIBLE);
        isLink = true;
        this.url = url;
        this.title = title;
        this.imgUrl= image;
        this.subTitle = desc;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_new_share_common);
        ButterKnife.bind(this);
        setCanceledOnTouchOutside(true);

        ((LinearLayout.LayoutParams) shareClose.getLayoutParams()).setMargins(0, ScreenUtils.dp2px(14) +
                ImmersionBar.getStatusBarHeight(context), ScreenUtils.dp2px(14) , 0);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Window window = getWindow();
        WindowManager.LayoutParams windowparams = window.getAttributes();
        windowparams.width = ScreenUtils.getScreenWidth();
        windowparams.height = WindowManager.LayoutParams.MATCH_PARENT;
        if (showBottom){
            window.setGravity(Gravity.BOTTOM);
            window.setBackgroundDrawableResource(R.color.black_99);
            window.setAttributes(windowparams);
            window.setWindowAnimations(R.style.bottomShow);
        }else {
            window.setGravity(Gravity.CENTER);
            window.setBackgroundDrawableResource(R.color.black_99);
            window.setType(WindowManager.LayoutParams.TYPE_APPLICATION_PANEL);
            window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

            window.setAttributes(windowparams);
        }
    }

    @OnClick({R.id.share_pic_rl, R.id.share_scroll,
            R.id.ll_wx, R.id.ll_pyq, R.id.ll_qr, R.id.share_close, R.id.ll_wx_link, R.id.ll_pyq_link})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.share_pic_rl:
                dismiss();
                break;
            case R.id.share_scroll:
                break;
            case R.id.ll_wx:
                if (Tools.isAppAvilible(context,"com.tencent.mm")) {
                    shareToWx();
                } else {
                    ToastUtil.showToast("请先安装微信客户端");
                }
                break;
            case R.id.ll_pyq:
                if (Tools.isAppAvilible(context,"com.tencent.mm")) {
                    shareToPyq();
                } else {
                    ToastUtil.showToast("请先安装微信客户端");
                }
                break;
            case R.id.ll_wx_link:
                if (Tools.isAppAvilible(context,"com.tencent.mm")) {
                    isLink = true;
                    shareToWx();
                } else {
                    ToastUtil.showToast("请先安装微信客户端");
                }
                break;
            case R.id.ll_pyq_link:
                if (Tools.isAppAvilible(context,"com.tencent.mm")) {
                    isLink = true;
                    shareToPyq();
                } else {
                    ToastUtil.showToast("请先安装微信客户端");
                }
                break;
            case R.id.ll_qr:
                boolean hasPermissions = rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                if (!hasPermissions){
                    new PermissionDialog(context, "开启相册权限", "保存图片需要获取保存到相册权限，请在下一个页面点击“允许”",
                            R.mipmap.icon_permission_storage, () -> requestPermissions()).show();
                }else {
                    savePic();
                }
                break;
            case R.id.share_close:
                dismiss();
                break;
            default:
        }
    }

    private void requestPermissions(){
        rxPermissions
                .requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(permission -> {
                    if (permission.granted) {
                        savePic();
                    } else if (permission.shouldShowRequestPermissionRationale) {
                    } else {
                        Toast.makeText(context, "保存文件权限申请失败,无法保存图片", Toast.LENGTH_SHORT).show();
                    }
                    dismiss();
                });
    }

    private void savePic(){
        Bitmap bitmap = toCompositeBitmap(getBitmap());
        if (bitmap == null) return;
        boolean result = UIUtils.saveImageToGallery(context, bitmap);
        if (result) {
            Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show();
        }
        bitmap.recycle();
    }

    private void requestPermissions(boolean isSession){
        rxPermissions
                .requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(permission -> {
                    if (permission.granted) {
                        savePic(isSession);
                    } else if (permission.shouldShowRequestPermissionRationale) {
                    } else {
                        Toast.makeText(context, "保存文件权限申请失败,无法保存图片", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void savePic(boolean isSession){
        Bitmap bitmap = toCompositeBitmap(getBitmap());
        if (bitmap == null) return;
        String path = UIUtils.getSaveImagePath(context, bitmap);
        if (WeiXinManager.checkVersionValid(context) && WeiXinManager.checkAndroidNotBelowN()) {
            path = WeiXinManager.getFileUri(context, new File(path));
        }
        if (!TextUtils.isEmpty(path)) {
            wxSharePic("he" + System.currentTimeMillis(),isSession,bitmap, path);
        } else {
            Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show();
        }
        bitmap.recycle();
    }

    private String hide_url_friend_circle = "0";
    public void setHide_url_friend_circle(String hide_url_friend_circle){
        this.hide_url_friend_circle = hide_url_friend_circle;
        llPyq.setVisibility("1".equals(hide_url_friend_circle)?View.GONE:View.VISIBLE);
    }

    private void switchTab() {
        if (isLink == false) return;
        isLink = false;
        shareClose.setVisibility(View.VISIBLE);
        llQr.setVisibility(View.VISIBLE);
        shareScroll.setVisibility(View.VISIBLE);
        llPyq.setVisibility(View.VISIBLE);
    }

    private void shareToWx() {
        if (!TextUtils.isEmpty(SPUtils.getInstance().getString(Config.CUSTOMER_TOKEN))) {
            taskShare();
        }
        if (isLink) {
            if ("2".equals(jump_type)) {
                WXMiniProgramObject miniProgram = new WXMiniProgramObject();
                miniProgram.webpageUrl = StringsUtils.urlAddParameters(url, map);// 兼容低版本的网页链接
                miniProgram.userName = ORIGINAL_ID;// 小程序原始id
                miniProgram.path = StringsUtils.urlAddParameters(path, map);//小程序页面路径
                if (BuildConfig.DEBUG){
                    miniProgram.miniprogramType = WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_TEST;
                }else {
                    miniProgram.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;
                }
                WXMediaMessage mediaMessage = new WXMediaMessage(miniProgram);
                mediaMessage.title = title;//自定义
                mediaMessage.description = "";//自定义
                if (TextUtils.isEmpty(mini_program_url)){
                    mini_program_url = imgUrl;
                }
                shareBitMap(mini_program_url, mediaMessage);
            } else {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        byte[] imgByte = null;
                        if (!TextUtils.isEmpty(imgUrl)) {
                            Bitmap bitmap = Utils.getSharePic(imgUrl);
                            if (bitmap != null) {
                                imgByte = Utils.bmpToByteArray(bitmap,32);
                            }
                        }
                        byte[] finalImgByte = imgByte;
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                WXWebpageObject webpage = new WXWebpageObject();
                                webpage.webpageUrl = StringsUtils.urlAddParameters(url, map);
                                WXMediaMessage msg = new WXMediaMessage(webpage);
                                msg.title = title;
                                msg.description = subTitle;
                                if (finalImgByte != null) {
                                    msg.thumbData = finalImgByte;
                                }
                                SendMessageToWX.Req rep = new SendMessageToWX.Req();
                                rep.message = msg;
                                rep.scene = SendMessageToWX.Req.WXSceneSession;
                                IWXAPI api = WXAPIFactory.createWXAPI(context, APP_ID);
                                api.sendReq(rep);
                            }
                        });
                    }
                }).start();
            }
        } else {
//            wechatSp.setShareType(Platform.SHARE_IMAGE);
//            wechatSp.setImageData(toCompositeBitmap(getBitmap()));
            shareAndSavePic(true);
        }
    }

    @SuppressLint("CheckResult")
    private void shareAndSavePic(boolean isSession){
        boolean hasPermissions = rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (!hasPermissions){
            new PermissionDialog(context, "开启相册权限", "保存图片需要获取保存到相册权限，请在下一个页面点击“允许”",
                    R.mipmap.icon_permission_storage, () -> requestPermissions(isSession)).show();
        }else {
            savePic(isSession);
        }
    }

    private void wxSharePic(String transaction,boolean isSession,Bitmap bitmap, String path) {
        //初始化WXImageObject和WXMediaMessage对象
        WXImageObject imageObject;
        if (!StringUtil.isBlank(path)) {
            imageObject = new WXImageObject();
            imageObject.imagePath = path;
        } else {
            imageObject = new WXImageObject(bitmap);
        }
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imageObject;
        //设置缩略图
        Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 200, 200, true);
        bitmap.recycle();
        msg.thumbData = Utils.bmpToByteArray(scaledBitmap,false);
        //构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = transaction + Long.toString(System.currentTimeMillis());
        req.message = msg;
        //表示发送给朋友圈  WXSceneTimeline  表示发送给朋友  WXSceneSession
        req.scene = isSession ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
        //调用api接口发送数据到微信
        IWXAPI api = WXAPIFactory.createWXAPI(context, APP_ID);
        api.sendReq(req);
    }

    private Bitmap mBitmap;

    public void shareBitMap(final String url, WXMediaMessage mediaMessage) {
        if (!TextUtils.isEmpty(url)) {
            Utils.getBitmapResources(context, url, new LoadCallBack<Bitmap>() {
                @Override
                public void loadSuccess(Bitmap mData) {
                    if (mData != null) {
                        mediaMessage.thumbData = bmpToByteArray(mData, false);// 小程序消息封面图片，小于128k
                        SendMessageToWX.Req req = new SendMessageToWX.Req();
                        req.message = mediaMessage;
                        req.scene = SendMessageToWX.Req.WXSceneSession;  // 目前只支持会话
                        IWXAPI api = WXAPIFactory.createWXAPI(context, APP_ID);
                        api.sendReq(req);
                    }
                }

                @Override
                public void loadFail() {
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast toast = Toast.makeText(context, "分享的图片失效", Toast.LENGTH_LONG);
                            toast.setGravity(Gravity.CENTER, 0, 0);
                            toast.show();
                        }
                    });
                }
            });
        }
    }

    private void shareToPyq() {
        if (!TextUtils.isEmpty(SPUtils.getInstance().getString(Config.CUSTOMER_TOKEN))) {
            taskShare();
        }
        if (isLink) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    byte[] imgByte = null;
                    if (!TextUtils.isEmpty(imgUrl)) {
                        Bitmap bitmap = Utils.getSharePic(imgUrl);
                        if (bitmap != null) {
                            imgByte = Utils.bmpToByteArray(bitmap,32);
                        }
                    }
                    byte[] finalImgByte = imgByte;
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            WXWebpageObject webpage = new WXWebpageObject();
                            webpage.webpageUrl = StringsUtils.urlAddParameters(url, map);
                            WXMediaMessage msg = new WXMediaMessage(webpage);
                            msg.title = title;
                            msg.description = subTitle;
                            if (finalImgByte != null) {
                                msg.thumbData = finalImgByte;
                            }
                            SendMessageToWX.Req rep = new SendMessageToWX.Req();
                            rep.message = msg;
                            rep.scene = SendMessageToWX.Req.WXSceneTimeline;
                            IWXAPI api = WXAPIFactory.createWXAPI(context, APP_ID);
                            api.sendReq(rep);
                        }
                    });
                }
            }).start();
        } else {
            shareAndSavePic(false);
        }
    }

    public Bitmap getBitmap() {
        int h = 0;
        Bitmap bitmap = null;
        for (int i = 0; i < shareScroll.getChildCount(); i++) {
            h += shareScroll.getChildAt(i).getHeight();
        }
        bitmap = Bitmap.createBitmap(shareScroll.getWidth(), h, Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(bitmap);
        Drawable background = shareScroll.getBackground();
        if (background instanceof ColorDrawable) {
            ColorDrawable colorDrawable = (ColorDrawable) background;
            int color = colorDrawable.getColor();
            canvas.drawColor(color);
        }
        shareScroll.draw(canvas);
        return bitmap;
    }


    public ShareCallback shareCallback;

    public interface ShareCallback {
        void onShare(int status);
    }

    public interface DismissCallback {
        void dismiss();
    }

    DismissCallback dismissCallback;
    public void setOnDismissCallback(DismissCallback dismissCallback){
        this.dismissCallback = dismissCallback;
    }


    /**
     * 成功
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void wxSendSuccess(WXSendSuccessEvent successEvent) {

        if (shareCallback != null) {
            shareCallback.onShare(0);
        }
        Toast.makeText(context, "分享成功", Toast.LENGTH_LONG).show();
        dismiss();

    }

    /**
     * 取消
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void wxSendCancel(WXSendCancelEvent cancelEvent) {
        if (shareCallback != null) {
            shareCallback.onShare(1);
        }
        Toast.makeText(context, "分享取消", Toast.LENGTH_LONG).show();
        dismiss();

    }

    /**
     * 失败
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void wxSendFailed(WXSendFailedEvent failedEvent) {
        if ("2".equals(jump_type)) {
            return;
        }
        if (shareCallback != null) {
            shareCallback.onShare(2);
        }
        Toast.makeText(context, "分享失败", Toast.LENGTH_LONG).show();
        dismiss();
    }

    @Override
    public void show() {
        EventBusManager.register(this);
        super.show();
    }

    @Override
    public void dismiss() {
        super.dismiss();
        EventBusManager.unRegister(this);
        if (dismissCallback != null) dismissCallback.dismiss();
        if (disposable != null) disposable.dispose();
    }

    public void taskShare() {
        String time = SPUtils.getInstance().getString(Config.TASK_TIME_SHARE_GOODS, "");
        final int[] count = {SPUtils.getInstance().getInt(Config.TASK_TIME_SHARE_COUNT, 0)};
        if (shareType == 0 && (TextUtils.isEmpty(time) ||
                !TimeUtil.isSameDay(System.currentTimeMillis() + "", time) ||
                (TimeUtil.isSameDay(System.currentTimeMillis() + "", time) && count[0] < 10))) {
            disposable = RetrofitUtil.getInstance().taskComplete("9").subscribeOn(Schedulers.io())
                    .unsubscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<CommonBaseBean>() {
                        @Override
                        public void accept(CommonBaseBean baseBean) throws Exception {
                            if ("0".equals(baseBean.getCode())) {
                                count[0]++;
                                if ( !TimeUtil.isSameDay(System.currentTimeMillis() + "", time)){
                                    count[0] = 1;
                                }
                                SPUtils.getInstance().put(Config.TASK_TIME_SHARE_COUNT, count[0]);
                                SPUtils.getInstance().put(Config.TASK_TIME_SHARE_GOODS, System.currentTimeMillis() + "");
                            } else {
                                SPUtils.getInstance().put(Config.TASK_TIME_SHARE_GOODS, "");
                            }
                        }
                    }, new ThrowableConsumer());

        }
    }

    public Bitmap toCompositeBitmap(Bitmap foreground) {
        int bgWidth = foreground.getWidth();
        int bgHeight = foreground.getHeight();
        Bitmap newbmp = Bitmap.createBitmap(bgWidth, bgHeight, Bitmap.Config.ARGB_8888);
        Canvas cv = new Canvas(newbmp);
        cv.drawColor(context.getResources().getColor(R.color.white));
        cv.drawBitmap(foreground, 0, 0, null);
        cv.save();//保存
        return newbmp;
    }

}
